﻿using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Xml;
using System.Xml.Linq;

namespace DynamicPropertyDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        XmlDynamicProperties dynamicProps;
        XElement root;
        public MainWindow()
        {
            InitializeComponent();
            // 假设你的XML文件名为"config.xml"
            var doc = XDocument.Load("config.xml");
            root = doc.Root;

            dynamicProps = new XmlDynamicProperties(root);
            propertyGrid.SelectedObject = dynamicProps;
            propertyGrid.PreparePropertyItem += PropertyGrid_PreparePropertyItem; ;
        }

        private void PropertyGrid_PreparePropertyItem(object sender, Xceed.Wpf.Toolkit.PropertyGrid.PropertyItemEventArgs e)
        {
            var item = e.Item as Xceed.Wpf.Toolkit.PropertyGrid.PropertyItem;
            if (item == null)
                return;
            if (item.PropertyType == typeof(XmlDynamicProperties))
            {
                e.PropertyItem.IsExpandable = true;
            }
            Console.WriteLine($"{item.PropertyName} ___{item.PropertyType}");
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var mt = root;
            var mkt = dynamicProps;
        }
    }

}
public static class XmlConverter
{
    public static dynamic ConvertToExpando(XElement element)
    {
        var result = new ExpandoObject() as IDictionary<string, object>;
        foreach (var child in element.Elements())
        {
            if (child.HasElements)
            {
                // 如果子元素有更多子元素，则递归处理
                result[child.Name.LocalName] = ConvertToExpando(child);
            }
            else
            {
                // 否则直接添加属性
                result[child.Name.LocalName] = child.Value;
            }
        }
        return result as ExpandoObject;
    }
}
